#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
结果查看器 - 用于查看和分析处理结果
"""

import json
import os
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional


class ResultViewer:
    """处理结果查看器"""
    
    def __init__(self, storage_root: str = "storage"):
        self.storage_root = Path(storage_root)
    
    def list_all_sessions(self):
        """列出所有处理会话"""
        if not self.storage_root.exists():
            print("没有找到存储目录")
            return
        
        sessions = []
        for session_dir in self.storage_root.iterdir():
            if session_dir.is_dir() and session_dir.name.startswith("session_"):
                summary_file = session_dir / "storage_summary.json"
                if summary_file.exists():
                    with open(summary_file, 'r', encoding='utf-8') as f:
                        summary = json.load(f)
                    sessions.append({
                        'session_id': summary['session_id'],
                        'timestamp': summary['timestamp'],
                        'original_file': summary['original_file'],
                        'total_elements': summary['statistics']['total_elements']
                    })
        
        # 按时间排序
        sessions.sort(key=lambda x: x['timestamp'], reverse=True)
        
        print(f"找到 {len(sessions)} 个处理会话:")
        print("-" * 80)
        print(f"{'会话ID':<30} {'时间':<20} {'文件':<20} {'元素数':<10}")
        print("-" * 80)
        
        for session in sessions:
            timestamp = datetime.fromisoformat(session['timestamp']).strftime('%Y-%m-%d %H:%M')
            print(f"{session['session_id']:<30} {timestamp:<20} {session['original_file']:<20} {session['total_elements']:<10}")
    
    def show_session_summary(self, session_id: str):
        """显示指定会话的详细摘要"""
        session_dir = self.storage_root / session_id
        summary_file = session_dir / "storage_summary.json"
        
        if not summary_file.exists():
            print(f"会话 {session_id} 不存在或没有摘要文件")
            return
        
        with open(summary_file, 'r', encoding='utf-8') as f:
            summary = json.load(f)
        
        print(f"会话详情: {session_id}")
        print("=" * 60)
        print(f"原始文件: {summary['original_file']}")
        print(f"处理时间: {summary['timestamp']}")
        print(f"存储路径: {summary['storage_path']}")
        print()
        
        # 统计信息
        stats = summary['statistics']
        print("元素统计:")
        print("-" * 30)
        print(f"总元素数: {stats['total_elements']}")
        print(f"文本元素: {stats['categories']['text']}")
        print(f"图像元素: {stats['categories']['image']}")
        print(f"表格元素: {stats['categories']['table']}")
        print()
        
        # 子类别统计
        print("详细分类:")
        print("-" * 30)
        for subcat, count in stats['subcategories'].items():
            print(f"{subcat}: {count}")
        print()
        
        # 三级标题分组
        if 'level3_groups' in stats:
            groups = stats['level3_groups']
            print(f"三级标题分组: {groups['count']} 个组")
            print("-" * 30)
            
            # 按元素数量排序显示前10个组
            sorted_groups = sorted(groups['groups'].items(), 
                                 key=lambda x: x[1]['element_count'], 
                                 reverse=True)
            
            print("元素最多的前10个组:")
            for i, (group_name, group_data) in enumerate(sorted_groups[:10]):
                print(f"{i+1:2d}. {group_name}: {group_data['element_count']} 个元素")
                categories = group_data['categories']
                cat_str = ", ".join([f"{k}:{v}" for k, v in categories.items()])
                print(f"    ({cat_str})")
    
    def show_group_content(self, session_id: str, group_name: str):
        """显示指定组的内容"""
        session_dir = self.storage_root / session_id
        group_file = session_dir / "text" / "level3_groups" / f"group_{group_name.replace('.', '_')}.json"
        
        if not group_file.exists():
            print(f"组文件不存在: {group_file}")
            return
        
        with open(group_file, 'r', encoding='utf-8') as f:
            group_data = json.load(f)
        
        print(f"组内容: {group_name}")
        print("=" * 60)
        print(f"元素数量: {len(group_data)}")
        print()
        
        # 显示前几个元素作为示例
        for i, element in enumerate(group_data[:5]):
            print(f"元素 {i+1}:")
            print(f"  类型: {element.get('type', 'unknown')}")
            print(f"  页码: {element.get('page', 'unknown')}")
            if 'content' in element:
                content = element['content'][:100] + "..." if len(element['content']) > 100 else element['content']
                print(f"  内容: {content}")
            print()
        
        if len(group_data) > 5:
            print(f"... 还有 {len(group_data) - 5} 个元素")
    
    def export_summary_report(self, session_id: str, output_file: str = None):
        """导出摘要报告"""
        session_dir = self.storage_root / session_id
        summary_file = session_dir / "storage_summary.json"
        
        if not summary_file.exists():
            print(f"会话 {session_id} 不存在")
            return
        
        if not output_file:
            output_file = f"report_{session_id}.txt"
        
        with open(summary_file, 'r', encoding='utf-8') as f:
            summary = json.load(f)
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(f"AIDA Framework 处理报告\n")
            f.write(f"{'='*50}\n\n")
            f.write(f"会话ID: {summary['session_id']}\n")
            f.write(f"原始文件: {summary['original_file']}\n")
            f.write(f"处理时间: {summary['timestamp']}\n")
            f.write(f"存储路径: {summary['storage_path']}\n\n")
            
            stats = summary['statistics']
            f.write(f"处理统计:\n")
            f.write(f"总元素数: {stats['total_elements']}\n")
            f.write(f"文本元素: {stats['categories']['text']}\n")
            f.write(f"图像元素: {stats['categories']['image']}\n")
            f.write(f"表格元素: {stats['categories']['table']}\n\n")
            
            f.write(f"详细分类:\n")
            for subcat, count in stats['subcategories'].items():
                f.write(f"{subcat}: {count}\n")
        
        print(f"报告已导出到: {output_file}")


if __name__ == "__main__":
    # 简单的命令行接口
    import sys
    
    viewer = ResultViewer()
    
    if len(sys.argv) == 1:
        viewer.list_all_sessions()
    elif len(sys.argv) == 2:
        viewer.show_session_summary(sys.argv[1])
    elif len(sys.argv) == 3 and sys.argv[1] == "group":
        # python result_viewer.py group session_id group_name
        pass
    else:
        print("用法:")
        print("  python result_viewer.py                    # 列出所有会话")
        print("  python result_viewer.py <session_id>       # 查看会话详情")